package com.zyx.comment.service.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RocketMQMessageListener(topic = "news-topic",
        consumerGroup = "news-consumer-group",
        selectorType = SelectorType.TAG,
        selectorExpression = "NEW||DEL",
        instanceName = "NewsMessageConsumerEx",
        consumeMode = ConsumeMode.CONCURRENTLY) // 并发消费模式
public class NewsMessageConsumerEx implements RocketMQListener<String> {

    @Override
    public void onMessage(String message) {
        try {
            //String news = new String(message.getBody());
//            System.out.println("处理新闻: " + message);
            log.info("处理新闻: " + message);

            // 业务处理成功，确认消费

        } catch (Exception e) {
            System.err.println("支付处理失败: " + e.getMessage());

            // 根据业务决定是否重试
//            if (shouldReconsume(message)) {
//                // 根据业务决定是否重试
//            } else {
//                // 不再重试，直接跳过
//                throw new RuntimeException("不再重试，直接跳过消息");
//            }
        }
    }

    private boolean shouldReconsume(MessageExt message) {
        // 检查重试次数
        int reconsumeTimes = message.getReconsumeTimes();
        log.info("尝试消费消息：{}次", reconsumeTimes);
        return reconsumeTimes < 3; // 最多重试3次
    }
}